﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AMS.DD35.WebMVC3
{
    public static class EnumHelper
    {
        public static IEnumerable<SelectListItem> ToSelectListItems<T>() where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");

            //var items = Enum.GetValues(typeof(T)).Cast<T>().Select(e => new { Value = e.ToString(), Text = e.ToString() }).ToList();

            List<SelectListItem> items = new List<SelectListItem>();
            foreach (int t in Enum.GetValues(typeof(T)))
            {
                SelectListItem item = new SelectListItem();
                item.Text = Enum.GetName(typeof(T), t);
                item.Value = Enum.GetName(typeof(T), t);
                items.Add(item);
            }
            return items;
        }

        public static IEnumerable<SelectListItem> ToSelectListItems<T>(T selectedValue) where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
                throw new ArgumentException("T must be an enumerated type");

            //var items = Enum.GetValues(typeof(T)).Cast<T>().Select(e => new { Value = e.ToString(), Text = e.ToString() }).ToList();

            List<SelectListItem> items = new List<SelectListItem>();
            foreach (int t in Enum.GetValues(typeof(T)))
            {
                SelectListItem item = new SelectListItem();
                item.Text = Enum.GetName(typeof(T), t);
                item.Value = Enum.GetName(typeof(T), t);
                if (selectedValue.Equals(t))
                    item.Selected = true;
                items.Add(item);
            }
            return items;
        }

        public static SelectList ToSelectList<T>() where T : struct, IConvertible
        {
            return new SelectList(ToSelectListItems<T>(), "Value", "Text");
        }
    }
}